package com.jqsoft.launcher.activity.majorPsychosis;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.widget.Toast;

import com.jqsoft.launcher.activity.WebViewActivity;
import com.jqsoft.launcher.activity.bean.MajorPsychosis_PersonBean;
import com.jqsoft.launcher.activity.bean.UserLoginInfo;
import com.jqsoft.launcher.common.BphsConstants;
import com.jqsoft.launcher.common.BphsURL;
import com.jqsoft.launcher.util.CommonUtil;
import com.jqsoft.launcher.util.DateTools;
import com.jqsoft.launcher.util.FileService;
import com.jqsoft.launcher.util.Log;
import com.jqsoft.launcher.util.MessageTools;
import com.jqsoft.launcher.util.StringTools;
import com.jqsoft.launcher.util.WebServiceUtils;

import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class MajorPsychosisFollowUpActivity3 extends WebViewActivity implements
View.OnClickListener {

	MajorPsychosis_PersonBean personInfo;
	String jsonstr = null;
	UserLoginInfo info = UserLoginInfo.getInstances();
	private int updateIndex=-1;
	private String sPersonID1;
	private String sNo1;//档案编号
	private String sname1;//姓名
	private String sCardNo1;//证件号码
	private String ishuixian="0";
	private String sAreaCode,sAreaName;
	@Override
	protected void initGui() {
		super.initGui();
		webView.loadUrl("file:///android_asset/jsb_followup_record.html");
		webView.addJavascriptInterface(new JSObject(), "contact");
	}

	@Override
	protected void initAction() {
		setGoBack();
	}

	@Override
	protected void initData() {
		setTitle("重性精神疾病患者随访服务记录表");
		Intent intent = getIntent();
        Bundle bundle=intent.getExtras();
        if(bundle!=null){
//         tijiaosf= (TiJiaoSFBean) bundle.get("TiJiaoSFBean");
         personInfo= (MajorPsychosis_PersonBean) bundle.get("MPGuanLi_PersonInfo");
          jsonstr=bundle.getString("Tjdata");
          sPersonID1=bundle.getString("sPersonID");
          sNo1=bundle.getString("sNo");
          sname1=bundle.getString("sname");
          sCardNo1=bundle.getString("sCardNo");
          updateIndex=bundle.getInt("chakan");

//        上次回显
          if(StringTools.isEmpty(jsonstr)){
         	 jsonstr=bundle.getString("shangciData");
         	 if(StringTools.isNotEmpty(jsonstr)){
         	 ishuixian="1";
         	 }
          }
        }
	}

	@Override
	public void onClick(View v) {
	}

	private final class JSObject {
		//初始化页面
		@JavascriptInterface
		public void getHtml() {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					try {
						Map<String, String> map = new HashMap<String, String>();
						map.put("PsychosisFollowUp_sRisk", "sRisk"); //危险性级别
						map.put("PsychosisFollowUp_sNowDiagnostics", "sNowDiagnostics");//目前症状
						map.put("PsychosisFollowUp_sInsight", "sInsight");//自知力
						map.put("PsychosisFollowUp_sSleep", "sSleep");//睡眠情况
						map.put("PsychosisFollowUp_sDiet", "sDiet");//饮食情况
						map.put("PsychosisFollowUp_sPersonalLifeFood", "sPersonalLifeFood");//个人生活料理
						map.put("PsychosisFollowUp_sHousework", "sHousework");//家务劳动
						map.put("PsychosisFollowUp_sProductiveWork", "sProductiveWork");//生产劳动及工作
						map.put("PsychosisFollowUp_sLearningAbility", "sLearningAbility");//学习能力
						map.put("PsychosisFollowUp_sInterpersonal", "sInterpersonal");//社会人际交往
						map.put("PsychosisPersonInfo_FInf", "sFamilyInfluence");//患病对家庭社会的影响
						map.put("PsychosisFollowUp_sCaptivity", "sCaptivity");//关锁情况
						map.put("PsychosisFollowUp_sHospitalSituation", "sHospitalSituation");//住院情况
						map.put("PsychosisFollowUp_sLaboratoryExamination", "sLaboratoryExamination");//实验室检查情况
						map.put("PsychosisFollowUp_sDrugCompliance", "sDrugCompliance");//药物依从性
						map.put("PsychosisFollowUp_sAdverseDrugReaction", "sAdverseDrugReaction");//药物不良反应
						map.put("PsychosisFollowUp_sTreatmentEffect", "sTreatmentEffect");//治疗效果
						map.put("PsychosisFollowUp_sReferral", "sReferral");//是否转诊
						map.put("PsychosisFollowUp_sRehabilitationMeasures", "sRehabilitationMeasures");//康复措施
						map.put("PsychosisFollowUp_sFollowUpClassification", "sFollowUpClassification");//此次随访分类
						JSONObject jsonObj = CommonUtil.getAllDictionary(map);
						if(personInfo!=null){
							jsonObj.put("sName", personInfo.getsPersonName());  //页面回显姓名
						}
						jsonObj.put("dFollowUpTime", DateTools.getFormatStringByDF_YYYY_MM_DD(new Date()));//页面回显随访日期
						jsonObj.put("dNextFollowUpTime", DateTools.getFormatStringByDF_YYYY_MM_DD(DateTools.getNextMonthByDate(new Date(),3)));//下次随访日期
						jsonObj.put("sNextVisitingPlace", info.getsOrganizationName());//随访单位
						jsonObj.put("DoctorList", info.getJsonArrayDoctors());//回显随访医生列表
						jsonObj.put("sDoctorName", info.getsUserName());//随访医生
						JSONArray jsonObj2=null;
						if(jsonstr!=null){
						jsonstr = jsonstr.replace("\n", "");
						jsonObj2= new JSONArray(jsonstr);
						for (int i = 0; i < jsonObj2.length() - 1; i++) {
							JSONObject o = (JSONObject) jsonObj2.get(i);
							sAreaCode = o.getString("sAreaCode");
						 	sAreaName = o.getString("sAreaName");
						}
						}
						// 初始化
						String json = jsonObj.toString();
						webView.loadUrl("javascript:showHtml('" + json + "','"+jsonObj2+"','"+ishuixian+"')");
//						webView.loadUrl("javascript:showHtml('" + json + "','"+jsonObj2+"')");
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
		}
		//保存操作
		@JavascriptInterface
		public void save(
				String uploadType,String sFollowUpClassification,String sRehabilitationMeasures,String sReferral,String sTreatmentEffect,String sAdverseDrugReaction,String sDrugCompliance,String sLaboratoryExamination,String sHospitalSituation,String sCaptivity,String sFamilyInfluence,String sInterpersonal,String sLearningAbility,String sProductiveWork,String sHousework,String sPersonalLifeFood,String sDiet,String sSleep,String sInsight,String sNowDiagnostics, String sRisk,
				String sName,String sRiskCode,String dFollowUpTime,String sNowDiagnosticsCode,String sNowDiagnosticsOther,String sInsightCode,String sSleepCode,String sDietCode,String sPersonalLifeFoodCode,String sHouseworkCode,
				String sProductiveWorkCode,String sLearningAbilityCode,String sInterpersonalCode,String sFamilyInfluenceCode,String iCauseTrouble,String iHit,String iZhaoHuo,String iSuicide,String iAttemptedSuicide,String sCaptivityCode,
				String sHospitalSituationCode,String dDischarge,String sLaboratoryExaminationCode,String sLaboratoryExaminationOther,String sDrugComplianceCode,String sAdverseDrugReactionCode,String sAdverseDrugReactionOther,String sTreatmentEffectCode,String sReferralCode,String sReferralreddason,
				String sRorganization,String sRehabilitationMeasuresCode,String sFollowUpClassificationCode,String sNextVisitingPlace,String sDoctorName,String dNextFollowUpTime,
				String sDrugName1,String iUsageDay1,String iDosage1,String sDrugName2,String iUsageDay2,String iDosage2,String sDrugName3,String iUsageDay3,String iDosage3,String sDrugQtdw1,String sDrugQtdw2,String sDrugQtdw3,String sDrug_qitadw1,String sDrug_qitadw2,String sDrug_qitadw3){
			try {

				String gKey = CommonUtil.getUUID();
				final JSONArray jsonArrayData = new JSONArray();
				JSONObject jsonData = new JSONObject();
				JSONObject jsonVistingInfo = new JSONObject();
				jsonVistingInfo.put("gKey", gKey);
				jsonVistingInfo.put("sPsychosisKey", "");//?
				jsonVistingInfo.put("MentalillnessKey", "");//?
				jsonVistingInfo.put("sName", sName);
				if(personInfo!=null){
					jsonVistingInfo.put("sPersonID", personInfo.getsPersonID());
					jsonVistingInfo.put("sNo", personInfo.getsNo());
				}else{
					jsonVistingInfo.put("sPersonID", sPersonID1);
					jsonVistingInfo.put("sNo", sNo1);
				}

				jsonVistingInfo.put("dFollowUpTime", dFollowUpTime);
				jsonVistingInfo.put("sRisk", sRisk);
				jsonVistingInfo.put("sRiskCode", sRiskCode);
				jsonVistingInfo.put("sNowDiagnostics", sNowDiagnostics);
				jsonVistingInfo.put("sNowDiagnosticsCode", sNowDiagnosticsCode);
				jsonVistingInfo.put("sNowDiagnosticsOther", sNowDiagnosticsOther);
				jsonVistingInfo.put("sInsight", sInsight);
				jsonVistingInfo.put("sInsightCode", sInsightCode);
				jsonVistingInfo.put("sSleep", sSleep);
				jsonVistingInfo.put("sSleepCode", sSleepCode);
				jsonVistingInfo.put("sDiet", sDiet);
				jsonVistingInfo.put("sDietCode", sDietCode);
				jsonVistingInfo.put("sPersonalLifeFood", sPersonalLifeFood);
				jsonVistingInfo.put("sPersonalLifeFoodCode", sPersonalLifeFoodCode);
				jsonVistingInfo.put("sHousework", sHousework);
				jsonVistingInfo.put("sHouseworkCode", sHouseworkCode);
				jsonVistingInfo.put("sProductiveWork", sProductiveWork);
				jsonVistingInfo.put("sProductiveWorkCode", sProductiveWorkCode);
				jsonVistingInfo.put("sLearningAbility", sLearningAbility);
				jsonVistingInfo.put("sLearningAbilityCode", sLearningAbilityCode);
				jsonVistingInfo.put("sInterpersonal", sInterpersonal);
				jsonVistingInfo.put("sInterpersonalCode", sInterpersonalCode);
				jsonVistingInfo.put("sFamilyInfluence", sFamilyInfluence);
				jsonVistingInfo.put("sFamilyInfluenceCode", sFamilyInfluenceCode);
				jsonVistingInfo.put("iCauseTrouble", iCauseTrouble);
				jsonVistingInfo.put("iHit", iHit);
				jsonVistingInfo.put("iZhaoHuo", iZhaoHuo);
				jsonVistingInfo.put("iSuicide", iSuicide);
				jsonVistingInfo.put("iAttemptedSuicide", iAttemptedSuicide);
				jsonVistingInfo.put("sCaptivity", sCaptivity);
				jsonVistingInfo.put("sCaptivityCode", sCaptivityCode);
				jsonVistingInfo.put("sHospitalSituation", sHospitalSituation);
				jsonVistingInfo.put("sHospitalSituationCode", sHospitalSituationCode);
				jsonVistingInfo.put("dDischarge", dDischarge);
				jsonVistingInfo.put("sLaboratoryExamination", sLaboratoryExamination);
				jsonVistingInfo.put("sLaboratoryExaminationCode", sLaboratoryExaminationCode);
				jsonVistingInfo.put("sLaboratoryExaminationOther", sLaboratoryExaminationOther);
				jsonVistingInfo.put("sDrugCompliance", sDrugCompliance);
				jsonVistingInfo.put("sDrugComplianceCode", sDrugComplianceCode);
				jsonVistingInfo.put("sAdverseDrugReaction", sAdverseDrugReaction);
				jsonVistingInfo.put("sAdverseDrugReactionCode", sAdverseDrugReactionCode);
				jsonVistingInfo.put("sAdverseDrugReactionOther", sAdverseDrugReactionOther);
				jsonVistingInfo.put("sTreatmentEffect", sTreatmentEffect);
				jsonVistingInfo.put("sTreatmentEffectCode", sTreatmentEffectCode);
				jsonVistingInfo.put("sReferral", sReferral);
				jsonVistingInfo.put("sReferralCode", sReferralCode);
				jsonVistingInfo.put("sReferralreason",sReferralreddason);
				jsonVistingInfo.put("sRorganization",sRorganization);
				jsonVistingInfo.put("sRehabilitationMeasures",sRehabilitationMeasures);
				jsonVistingInfo.put("sRehabilitationMeasuresCode",sRehabilitationMeasuresCode);
				jsonVistingInfo.put("sFollowUpClassification",sFollowUpClassification);
				jsonVistingInfo.put("sFollowUpClassificationCode",sFollowUpClassificationCode);
				jsonVistingInfo.put("dNextFollowUpTime",dNextFollowUpTime);
				jsonVistingInfo.put("sDoctorName",sDoctorName);
				jsonVistingInfo.put("sDoctorCode", "");
				jsonVistingInfo.put("sAreaCode", sAreaCode);
				jsonVistingInfo.put("sAreaName", sAreaName);
				jsonVistingInfo.put("sAddUser", info.getsLoginName());
				jsonVistingInfo.put("dAddTime", DateTools.getFormatStringByDF_YYYY_MM_DD_HH_MM_SS(new Date()));
				jsonVistingInfo.put("sUpdateUser", "");
				jsonVistingInfo.put("dUpdateTime", "");
				jsonVistingInfo.put("sDeleteUser", "");
				jsonVistingInfo.put("dDeleteTime", "");
				jsonVistingInfo.put("sInputDeptName", info.getsOrganizationName());
				jsonVistingInfo.put("sInputDeptCode", info.getsOrganizationKey());
				jsonVistingInfo.put("iState", 1);
				jsonVistingInfo.put("iVisitingTimes", 0);
				jsonVistingInfo.put("sVisitingDoctorCode", "");
				jsonVistingInfo.put("sNextVisitingPlace", sNextVisitingPlace);
				jsonVistingInfo.put("sVisitingPlaceCode", "");
				jsonArrayData.put(jsonVistingInfo);

				JSONArray jsonArray = new JSONArray();
				if(StringTools.isNotEmpty(sDrugName1)){
					JSONObject jsonObj = new JSONObject();
					jsonObj.put("gKey", CommonUtil.getUUID());
					jsonObj.put("gPsychosisFollowUpKey", gKey);
					if(personInfo!=null){
						jsonObj.put("sPersonID", personInfo.getsPersonID());
					}else{
						jsonObj.put("sPersonID", sPersonID1);
					}
					jsonObj.put("sDrugName", sDrugName1);
					jsonObj.put("iUsageDay", iUsageDay1);
					jsonObj.put("iUsageMonth", 2);//?
					jsonObj.put("iDosage", iDosage1);
					jsonObj.put("sAddUser", info.getsLoginName());
					jsonObj.put("dAddTime", DateTools.getFormatStringByDF_YYYY_MM_DD_HH_MM_SS(new Date()));
					jsonObj.put("sUpdateUser", "");
					jsonObj.put("dUpdateTime", "");
					jsonObj.put("sDeleteUser", "");
					jsonObj.put("dDeleteTime", "");
					jsonObj.put("sDrugQtdw", sDrugQtdw1);
					jsonObj.put("sDrug_qitadw", sDrug_qitadw1);
					jsonObj.put("sInputDeptName", info.getsOrganizationName());
					jsonObj.put("sInputDeptCode", info.getsOrganizationKey());
					jsonObj.put("iState", 1);
					jsonObj.put("sUnit", "");
					jsonObj.put("sort","1");
					jsonArray.put(jsonObj);
				}
				if(StringTools.isNotEmpty(sDrugName2)){
					JSONObject jsonObj = new JSONObject();
					jsonObj.put("gKey", CommonUtil.getUUID());
					jsonObj.put("gPsychosisFollowUpKey", gKey);
					if(personInfo!=null){
						jsonObj.put("sPersonID", personInfo.getsPersonID());
					}else{
						jsonObj.put("sPersonID", sPersonID1);
					}
					jsonObj.put("sDrugName", sDrugName2);
					jsonObj.put("iUsageDay", iUsageDay2);
					jsonObj.put("iUsageMonth", 2);//?
					jsonObj.put("iDosage", iDosage2);
					jsonObj.put("sAddUser", info.getsLoginName());
					jsonObj.put("dAddTime", DateTools.getFormatStringByDF_YYYY_MM_DD_HH_MM_SS(new Date()));
					jsonObj.put("sUpdateUser", "");
					jsonObj.put("dUpdateTime", "");
					jsonObj.put("sDeleteUser", "");
					jsonObj.put("dDeleteTime", "");
					jsonObj.put("sDrugQtdw", sDrugQtdw2);
					jsonObj.put("sDrug_qitadw", sDrug_qitadw2);
					jsonObj.put("sInputDeptName", info.getsOrganizationName());
					jsonObj.put("sInputDeptCode", info.getsOrganizationKey());
					jsonObj.put("iState", 1);
					jsonObj.put("sUnit", "");
					jsonObj.put("sort","2");
					jsonArray.put(jsonObj);
				}
				if(StringTools.isNotEmpty(sDrugName3)){
					JSONObject jsonObj = new JSONObject();
					jsonObj.put("gKey", CommonUtil.getUUID());
					jsonObj.put("gPsychosisFollowUpKey", gKey);
					if(personInfo!=null){
						jsonObj.put("sPersonID", personInfo.getsPersonID());
					}else{
						jsonObj.put("sPersonID", sPersonID1);
					}
					jsonObj.put("sDrugName", sDrugName3);
					jsonObj.put("iUsageDay", iUsageDay3);
					jsonObj.put("iUsageMonth", 2);//?
					jsonObj.put("iDosage", iDosage3);
					jsonObj.put("sAddUser", info.getsLoginName());
					jsonObj.put("dAddTime", DateTools.getFormatStringByDF_YYYY_MM_DD_HH_MM_SS(new Date()));
					jsonObj.put("sUpdateUser", "");
					jsonObj.put("dUpdateTime", "");
					jsonObj.put("sDeleteUser", "");
					jsonObj.put("dDeleteTime", "");
					jsonObj.put("sDrugQtdw", sDrugQtdw3);
					jsonObj.put("sDrug_qitadw", sDrug_qitadw3);
					jsonObj.put("sInputDeptName", info.getsOrganizationName());
					jsonObj.put("sInputDeptCode", info.getsOrganizationKey());
					jsonObj.put("iState", 1);
					jsonObj.put("sUnit", "");
					jsonObj.put("sort","3");
					jsonArray.put(jsonObj);
				}
				jsonData.put("sMedicalList", jsonArray);
				jsonArrayData.put(jsonData);
				Log.i("benny", jsonArrayData.toString());
				if("2".equals(uploadType)){
					MajorPsychosisFollowUpActivity3.this.runOnUiThread(new Runnable() {
						@Override
						public void run() {
							try {
								boolean issuccess=false;
								if(updateIndex>=0&&personInfo==null){

									 issuccess=new FileService(act).updateFromRom(updateIndex,sPersonID1, sNo1, sname1, sCardNo1, "重性精神疾病患者随访", jsonArrayData.toString(), "append.txt");
								}else{
								issuccess=new FileService(act).saveToRom(personInfo.getsPersonID(),personInfo.getsNo(),personInfo.getsPersonName(),personInfo.getsCardNo(), "重性精神疾病患者随访", jsonArrayData.toString(), "append.txt");
								} if(issuccess){
									MessageTools.showDialogOk(ctx, "保存成功！本次随访数据保存在本机，请到“离线设置”-“上传随访信息”中上传或者修改数据！");
								}else{
									 Toast.makeText(MajorPsychosisFollowUpActivity3.this, "保存失败！", Toast.LENGTH_SHORT).show();
								 }
							} catch (Exception e) {
								 Toast.makeText(MajorPsychosisFollowUpActivity3.this, "保存失败！", Toast.LENGTH_SHORT).show();
								e.printStackTrace();
							}
						}});
				}else if(BphsConstants.isNetAvailable&&"1".equals(uploadType)){
				MajorPsychosisFollowUpActivity3.this.runOnUiThread(new Runnable() {
					@Override
					public void run() {


						//创建了对话框的构造器
						Builder builder = new Builder(MajorPsychosisFollowUpActivity3.this);
						builder.setTitle("温馨提示");
						builder.setMessage("确定将本次随访数据提交至服务器吗？注意：提交后本条数据无法在平板上再次修改！");
						builder.setPositiveButton("确定", new OnClickListener() {

							public void onClick(DialogInterface dialog, int which) {
								try {
								String methodName = BphsURL.getCommonPath("AddPsychosisPersonVisiting_METHOD");
								String serviceURL = BphsURL.getCommonPath("AddPsychosisPersonVisiting_URL");
//								String methodName = "AddPsychosisPersonVisiting"; 
//								String serviceURL = "http://60.171.146.122:9098/WebService/Andrews/PsychosisPersonWebService.asmx";
								String result =	WebServiceUtils.requestByParams(methodName, jsonArrayData.toString(), serviceURL);
								if(StringUtils.isNotBlank(result)){
									JSONObject json = new JSONObject(result);
									 String sResult = json.getString("sSuccess");
									 if(sResult.equals("1")){
										 Toast.makeText(MajorPsychosisFollowUpActivity3.this, "保存完成！", Toast.LENGTH_SHORT).show();
									 }else{
										 Toast.makeText(MajorPsychosisFollowUpActivity3.this, "保存失败！", Toast.LENGTH_SHORT).show();
									 }
								}else{
									Toast.makeText(MajorPsychosisFollowUpActivity3.this, "远程服务器故障！", Toast.LENGTH_SHORT).show();
								}
							} catch (Exception e) {
								e.printStackTrace();
							}}
						});
						builder.setNegativeButton("取消", new OnClickListener() {

							public void onClick(DialogInterface dialog, int which) {
								 Toast.makeText(MajorPsychosisFollowUpActivity3.this, "保存失败！", Toast.LENGTH_SHORT).show();
							}
						});
						AlertDialog dialog =builder.create();
						dialog.setCancelable(false);
						dialog.setCanceledOnTouchOutside(false);
						dialog.show();
					}
					
				});}else{
					 Toast.makeText(MajorPsychosisFollowUpActivity3.this, "离线状态只能保存随访信息！", Toast.LENGTH_LONG).show();
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}
}
